<template>
  <div>
    <!-- 页面标题 -->
    <v-row class="mb-6">
      <v-col cols="12">
        <h1 class="text-h4 font-weight-bold">{{ $t('admin.afterSchoolClassManagement') }}</h1>
        <p class="text-subtitle-1 text-medium-emphasis">
          {{ $t('admin.afterSchoolClassManagementDescription') }}
        </p>
      </v-col>
    </v-row>

    <!-- 操作按钮 -->
    <v-row class="mb-6">
      <v-col cols="12" class="d-flex justify-end">
        <v-btn
          color="primary"
          variant="flat"
          prepend-icon="mdi-plus"
          @click="openClassDialog()"
        >
          {{ $t('admin.addAfterSchoolClass') }}
        </v-btn>
      </v-col>
    </v-row>

    <!-- 课后班级列表 -->
    <v-row>
      <v-col cols="12">
        <v-card>
          <v-card-title>
            <v-icon class="me-2">mdi-book-open-variant</v-icon>
            {{ $t('admin.afterSchoolClasses') }}
          </v-card-title>
          
          <v-card-text>
            <v-data-table
              :headers="classHeaders"
              :items="classes"
              :loading="loading"
              :no-data-text="$t('common.noData')"
              :loading-text="$t('common.loading')"
              class="elevation-1"
              :items-per-page="10"
              :items-per-page-options="[10, 20, 50]"
            >
              <!-- 班级名称列 -->
              <template v-slot:item.name="{ item }">
                <div class="d-flex align-center">
                  <v-icon class="me-2" color="orange">mdi-book-open-variant</v-icon>
                  <span>{{ item.name }}</span>
                </div>
              </template>

              <!-- 教师列 -->
              <template v-slot:item.teacher_name="{ item }">
                <v-chip size="small" color="blue" variant="flat">
                  <v-icon start size="small">mdi-account</v-icon>
                  {{ item.teacher_name }}
                </v-chip>
              </template>

              <!-- 操作列 -->
              <template v-slot:item.actions="{ item }">
                <v-btn
                  icon
                  variant="text"
                  color="primary"
                  size="small"
                  @click="openClassDialog(item)"
                >
                  <v-icon>mdi-pencil</v-icon>
                </v-btn>
                <v-btn
                  icon
                  variant="text"
                  color="error"
                  size="small"
                  @click="confirmDeleteClass(item)"
                >
                  <v-icon>mdi-delete</v-icon>
                </v-btn>
              </template>
            </v-data-table>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>

    <!-- 课后班级对话框 -->
    <v-dialog v-model="classDialog.show" max-width="600">
      <v-card>
        <v-card-title class="text-h5">
          {{ classDialog.isEdit ? $t('admin.editAfterSchoolClass') : $t('admin.addAfterSchoolClass') }}
        </v-card-title>
        <v-card-text>
          <v-form ref="classForm" @submit.prevent="saveClass">
            <v-row>
              <v-col cols="12">
                <v-text-field
                  v-model="classDialog.form.name"
                  :label="$t('common.name')"
                  :rules="[v => !!v || $t('validation.required')]"
                  variant="outlined"
                  required
                ></v-text-field>
              </v-col>
              <v-col cols="12">
                <v-textarea
                  v-model="classDialog.form.description"
                  :label="$t('common.description')"
                  variant="outlined"
                  rows="3"
                ></v-textarea>
              </v-col>
              <v-col cols="12">
                <v-select
                  v-model="classDialog.form.teacher_id"
                  :items="afterSchoolTeachers"
                  item-title="name"
                  item-value="id"
                  :label="$t('admin.selectTeacher')"
                  :rules="[v => !!v || $t('validation.required')]"
                  variant="outlined"
                  required
                ></v-select>
              </v-col>
            </v-row>
          </v-form>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn
            color="grey-darken-1"
            variant="text"
            @click="classDialog.show = false"
          >
            {{ $t('common.cancel') }}
          </v-btn>
          <v-btn
            color="primary"
            variant="flat"
            @click="saveClass"
            :loading="classDialog.loading"
          >
            {{ $t('common.save') }}
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- 删除确认对话框 -->
    <v-dialog v-model="deleteDialog.show" max-width="400">
      <v-card>
        <v-card-title class="text-h5">
          {{ $t('admin.confirmDelete') }}
        </v-card-title>
        <v-card-text>
          {{ $t('admin.deleteAfterSchoolClassConfirm', { name: deleteDialog.className }) }}
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn
            color="grey-darken-1"
            variant="text"
            @click="deleteDialog.show = false"
          >
            {{ $t('common.cancel') }}
          </v-btn>
          <v-btn
            color="error"
            variant="flat"
            @click="deleteClass"
            :loading="deleteDialog.loading"
          >
            {{ $t('common.delete') }}
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- 操作结果提示 -->
    <v-snackbar
      v-model="snackbar.show"
      :color="snackbar.color"
      :timeout="3000"
    >
      {{ snackbar.text }}
      <template v-slot:actions>
        <v-btn
          variant="text"
          @click="snackbar.show = false"
        >
          {{ $t('common.close') }}
        </v-btn>
      </template>
    </v-snackbar>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import api from '@/utils/api'

export default {
  name: 'AfterSchoolClassManagement',
  
  setup() {
    const { t } = useI18n()
    const classForm = ref(null)
    
    // 数据状态
    const loading = ref(false)
    const classes = ref([])
    const afterSchoolTeachers = ref([])
    
    // 班级对话框状态
    const classDialog = ref({
      show: false,
      isEdit: false,
      loading: false,
      form: {
        id: null,
        name: '',
        description: '',
        teacher_id: null
      }
    })
    
    // 删除对话框状态
    const deleteDialog = ref({
      show: false,
      loading: false,
      classId: null,
      className: ''
    })
    
    // 提示信息状态
    const snackbar = ref({
      show: false,
      text: '',
      color: 'success'
    })
    
    // 表格头部
    const classHeaders = computed(() => [
      { title: t('common.name'), key: 'name', sortable: true },
      { title: t('common.description'), key: 'description', sortable: false },
      { title: t('admin.teacher'), key: 'teacher_name', sortable: true },
      { title: t('common.actions'), key: 'actions', sortable: false, align: 'end' }
    ])
    
    // 获取课后班级列表
    const fetchClasses = async () => {
      loading.value = true
      try {
        const response = await api.get('/after-school/classes')
        classes.value = response.data.data.classes
      } catch (error) {
        console.error('获取课后班级列表失败:', error)
        showSnackbar(t('common.fetchError'), 'error')
      } finally {
        loading.value = false
      }
    }
    
    // 获取课后老师列表
    const fetchAfterSchoolTeachers = async () => {
      try {
        const response = await api.get('/after-school/teachers')
        afterSchoolTeachers.value = response.data.data
      } catch (error) {
        console.error('获取课后老师列表失败:', error)
        showSnackbar(t('common.fetchError'), 'error')
      }
    }
    
    // 打开班级对话框
    const openClassDialog = (classItem = null) => {
      if (classItem) {
        // 编辑模式
        classDialog.value.isEdit = true
        classDialog.value.form = {
          id: classItem.id,
          name: classItem.name,
          description: classItem.description || '',
          teacher_id: classItem.teacher_id,
          start_time: classItem.start_time,
          end_time: classItem.end_time
        }
      } else {
        // 新增模式
        classDialog.value.isEdit = false
        classDialog.value.form = {
          id: null,
          name: '',
          description: '',
          teacher_id: null,
          start_time: '',
          end_time: ''
        }
      }
      classDialog.value.show = true
    }
    
    // 保存班级
    const saveClass = async () => {
      // 表单验证
      const { valid } = await classForm.value.validate()
      if (!valid) return
      
      classDialog.value.loading = true
      try {
        if (classDialog.value.isEdit) {
          // 更新班级
          await api.put(`/after-school/classes/${classDialog.value.form.id}`, classDialog.value.form)
          showSnackbar(t('admin.classUpdated'), 'success')
        } else {
          // 创建班级
          await api.post('/after-school/classes', classDialog.value.form)
          showSnackbar(t('admin.classCreated'), 'success')
        }
        
        // 关闭对话框并刷新列表
        classDialog.value.show = false
        fetchClasses()
      } catch (error) {
        console.error('保存课后班级失败:', error)
        showSnackbar(t('common.saveError'), 'error')
      } finally {
        classDialog.value.loading = false
      }
    }
    
    // 确认删除班级
    const confirmDeleteClass = (classItem) => {
      deleteDialog.value.classId = classItem.id
      deleteDialog.value.className = classItem.name
      deleteDialog.value.show = true
    }
    
    // 删除班级
    const deleteClass = async () => {
      deleteDialog.value.loading = true
      try {
        await api.delete(`/after-school/classes/${deleteDialog.value.classId}`)
        showSnackbar(t('admin.classDeleted'), 'success')
        
        // 关闭对话框并刷新列表
        deleteDialog.value.show = false
        fetchClasses()
      } catch (error) {
        console.error('删除课后班级失败:', error)
        showSnackbar(t('common.deleteError'), 'error')
      } finally {
        deleteDialog.value.loading = false
      }
    }
    
    // 显示提示信息
    const showSnackbar = (text, color = 'success') => {
      snackbar.value = {
        show: true,
        text,
        color
      }
    }
    
    // 组件挂载时获取数据
    onMounted(() => {
      fetchClasses()
      fetchAfterSchoolTeachers()
    })
    
    return {
      loading,
      classes,
      afterSchoolTeachers,
      classHeaders,
      classDialog,
      deleteDialog,
      snackbar,
      classForm,
      fetchClasses,
      openClassDialog,
      saveClass,
      confirmDeleteClass,
      deleteClass
    }
  }
}
</script>